<template>
   <div >
        <el-card style="width: 800px;">
          <el-form ref="familyForm" :model="family" :rules="familyRules" label-width="120px">
        	<div class="form-row">
        	  <el-form-item class="form-item" label="户号"  style="width: 400px;" prop="fid">
        		<el-input v-model="family.fid" maxlength="10" placeholder="请输入贫困户编号" disabled></el-input>
        	  </el-form-item>
        	</div>
        	<div class="form-row">
        	  <el-form-item class="form-item" label="户主姓名" prop="pname">
        		<el-input v-model="family.headName" placeholder="请输入户主姓名" readonly @focus="handleEditAttempt('户主姓名')"></el-input>
        	  </el-form-item>
        	  <el-form-item class="form-item" label="户主身份证" prop="pnumber">
        		<el-input v-model="family.headIdNumber" placeholder="请输入户主身份证号" maxlength="18" readonly @focus="handleEditAttempt('户主身份证')"></el-input>
        	  </el-form-item>
        	</div>
        	<div class="form-row">
        	  <el-form-item class="form-item" label="省" prop="province">
        		<el-select v-model="family.province" @change="onProvinceChange">
        		  <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.name"></el-option>
        		</el-select>
        	  </el-form-item>
        	  <el-form-item class="form-item" label="市" prop="city">
        		<el-select v-model="family.city" @change="onCityChange">
        		  <el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.name"></el-option>
        		</el-select>
        	  </el-form-item>
        	</div>
        	<div class="form-row">
        	  <el-form-item class="form-item" label="县(区)" prop="county">
        		<el-select v-model="family.county" @change="onCountyChange">
        		  <el-option v-for="county in counties" :key="county.code" :label="county.name" :value="county.name"></el-option>
        		</el-select>
        	  </el-form-item>
        	  <el-form-item class="form-item" label="乡(镇)" prop="township">
        		<el-select v-model="family.township" @change="onTownshipChange">
        		  <el-option v-for="township in townships" :key="township.code" :label="township.name" :value="township.name"></el-option>
        		</el-select>
        	  </el-form-item>
        	</div>
        	<el-form-item label="村" prop="village">
        	  <el-input v-model="family.village" placeholder="请输入村名称"></el-input>
        	</el-form-item>
          </el-form>
        </el-card>
		<div class="save">
			 <el-button style="margin-top: 10px;" type="success" @click="submit" :icon="Save">提交</el-button>
		</div>
   </div>
</template>
  
<script setup>
import { ref ,onMounted ,watch ,reactive} from 'vue'
import Save from '@/components/icons/save' 
import { ElMessage } from 'element-plus'
import areaData from '@/area/pcas-code.json'
import { post, get } from '@/axios'
const emits = defineEmits(['update:show','getTableData'])
const props = defineProps(['id','idcard'])
const familyForm = ref(null) 
const family = ref({
  fid: null,
  pname: '',
  pnumber: '',
  rid: null,
  province: '',
  city: '',
  county: '',
  township: '',
  village: '',
  headName:'',
  headIdNumber:''
})

function checkFamily (rule, value, callback) {
	get("/family/check",{ id:props.id, value, field: 'f_id' }, content => {
		if (content) {
			callback()
		} else {
			callback(new Error())
		}
	})
}

const familyRules = reactive({
	county: [
		{ required: true, message: '请选择所在县(区)', trigger: 'blur' }
	],
	city: [
		{ required: true, message: '请选择所在城市', trigger: 'blur' }
	],
	province: [
		{ required: true, message: '请选择所在省份', trigger: 'blur' }
	],
	township: [
		{ required: true, message: '请选择所在乡(镇)', trigger: 'blur' }
	],
	village: [
		{ required: true, message: '请输入所在村庄', trigger: 'blur' }
	]
})

const provinces = ref([]);
const cities = ref([]);
const counties = ref([]);
const townships = ref([]);

onMounted(() => {
  provinces.value = areaData.map(province => ({
    name: province.name,
    code: province.code,
    cities: province.children || [],
  }));
});

// 选择省份后加载市
const onProvinceChange = (value) => {
  family.value.province = value;
  family.value.city = '';
  family.value.county = '';
  family.value.township = '';
  
  const selectedProvince = provinces.value.find(province => province.name === value);

  if (selectedProvince) {
    cities.value = selectedProvince.cities.map(city => ({
      name: city.name,
      code: city.code,
      counties: city.children || [],
    }));
  } else {
    cities.value = [];
  }

  counties.value = [];
  townships.value = [];
  family.value.rid = null;
};

// 选择市后加载县
const onCityChange = (value) => {
  family.value.city = value;
  family.value.county = '';
  family.value.township = '';

  const selectedCity = cities.value.find(city => city.name === value);

  if (selectedCity) {
    counties.value = selectedCity.counties.map(county => ({
      name: county.name,
      code: county.code,
      townships: county.children || [],
    }));
  } else {
    counties.value = [];
  }

  townships.value = [];
  family.value.rid = null;
};

// 选择县后加载乡
const onCountyChange = (value) => {
  family.value.county = value;
  family.value.township = '';

  const selectedCounty = counties.value.find(county => county.name === value);

  if (selectedCounty) {
    townships.value = selectedCounty.townships.map(township => ({
      name: township.name,
      code: township.code,
    }));
  } else {
    townships.value = [];
  }

  family.value.rid = null;
};

// 选择乡镇后绑定 rid
const onTownshipChange = (value) => {
  family.value.township = value;
  const townshipData = townships.value.find(township => township.name === value);
  family.value.rid = townshipData ? townshipData.code : null;
};

function submit () {
	console.dir(family)
	post('/family/update',family.value,content => {
		emits('update:show',false)
		emits('getTableData')
	},familyForm)
}

function handleEditAttempt (field) {
	ElMessage.warning(`您无法在这里修改${field},请在家庭成员处修改`)
} 

function getById () {
	get("/family/getById",{ id: props.id },content => {
		for (const key in family.value) {
			// Object.prototype.hasOwnProperty.call(content,key)这个函数是为了判断前端admin中的key在后端传回的数据中是否存在
			if (Object.prototype.hasOwnProperty.call(content,key)) {
				family.value[key] = content[key]
			}
		}
		  if (family.value.province) {
		    // 初始化市级数据
		    const selectedProvince = provinces.value.find(province => province.name === family.value.province);
		    if (selectedProvince) {
		      cities.value = selectedProvince.cities.map(city => ({
		        name: city.name,
		        code: city.code,
		        counties: city.children || [],
		      }));
		    }
		
		    if (family.value.city) {
		      // 初始化县级数据
		      const selectedCity = cities.value.find(city => city.name === family.value.city);
		      if (selectedCity) {
		        counties.value = selectedCity.counties.map(county => ({
		          name: county.name,
		          code: county.code,
		          townships: county.children || [],
		        }));
		      }
		
		      if (family.value.county) {
		        // 初始化乡级数据
		        const selectedCounty = counties.value.find(county => county.name === family.value.county);
		        if (selectedCounty) {
		          townships.value = selectedCounty.townships.map(township => ({
		            name: township.name,
		            code: township.code,
		          }));
		        }
		      }
		    }
		  }
	})
}
getById()

</script>
  
<style scoped lang="scss">
.form-row {
  display: flex;
  gap: 20px; 
  margin-top: 10px;
  .form-item {
    flex: 1; 
  }
}
.save {
	display: flex;
	justify-content: center;
	align-items: center;
}

</style>